<template>
	<view>
		<view>
			<view class="venueForm">
				<view>
					<view style="font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;">请上传场馆图片</view>
					<view style="color: #888888;font-size: 26rpx;line-height: 70rpx;">最多上传9张图，且图片宽高建议750*339px</view>
				</view>
				<view>
					<u-upload name="host" :fileList="hostList"  @afterRead="onUpload($event, 'host')"
							@delete="onDelete($event, 'host')"  :maxCount="9"
						width="208rpx" height="208rpx">
					</u-upload>
				</view>
			</view>
			<view class="height30 bg-f1f1f1"></view>
			<view class="venueForm">
				
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>公司名称</view>
						<input class="fvalue" v-model="venueInfo.companyName" placeholder="输入公司名称"  />
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>场馆名称</view>
						<input class="fvalue" v-model="venueInfo.venueName"  placeholder="输入场馆名称"  />
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>占地面积</view>
						<input class="fvalue" v-model="venueInfo.area" type="digit"  placeholder="输入占地面积"  />
						<view style="font-size: 25rpx;padding-right: 10rpx;">（㎡)</view>
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>联系人</view>
						<input class="fvalue"  v-model="venueInfo.contacts"  placeholder="输入场馆联系人"  />
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>联系电话</view>
						<input class="fvalue" v-model="venueInfo.phone" type="number"  placeholder="输入联系电话"  />
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>所属区域</view>
						<view class="fvalue" @click="pickerLocal.showLocal = true" >
							{{ (pickerLocal.local === '' ? '选择省/市/区' : pickerLocal.local) }}
						</view>
					</view>
				</view>
				<!-- <view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>详细地址</view>
						<input class="fvalue" v-model="venueInfo.address" type="text"  placeholder="输入联系电话"  />
					</view>
				</view> -->
				<view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>详细位置</view>
						<view class="fvalue" @click="selectChoose">{{ venueInfo.address || '选择详细位置' }}</view>
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row" style="display: block;">
						<view class="ftitle"><text class="required">*</text>场馆设施</view>
						<view style="padding: 0rpx 20rpx;">
							<view class="multiple">
								<view :class="{active: facilitieChooseList.indexOf(item.dictKey) >= 0}" v-for="item in facilitieList"
									:key="item.dictKey" @click="onChoosePlan(item)">
									{{item.dictValue}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row" style="display: block;">
						<view class="ftitle"><text class="required">*</text>场馆服务</view>
						<view style="padding: 0rpx 20rpx;">
							<view class="multiple">
								<view :class="{active: serviceChooseList.indexOf(item.dictKey) >= 0}" v-for="item in serviceList"
									:key="item.dictKey" @click="onChooseService(item)">
									{{item.dictValue}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="height30 bg-f1f1f1"></view>
			<view class="venueForm">
				<view class="textareaTitle"><text class="required">*</text>场馆介绍</view>
				<view style="border: 1px solid #c3c3c3; padding:20rpx;">
					<textarea v-model="venueInfo.venueDescription" style="height: 200rpx;font-size: 32rpx;" placeholder="请输入场馆介绍"></textarea>
				</view>
			</view>
			
			<view class="height30 bg-f1f1f1"></view>
			<view class="venueForm">
				<view class="textareaTitle"><text class="required">*</text>预约须知</view>
				<view style="border: 1px solid #c3c3c3;padding:20rpx;">
					<textarea v-model="venueInfo.reservationNotice" style="height: 200rpx;font-size: 32rpx;" placeholder="请输入预约须知"></textarea>
				</view>
			</view>
			
			<view class="height30 bg-f1f1f1"></view>
			<view class="venueForm">
				<view style="padding-bottom: 20rpx;font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;">场馆营业时间</view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>开始时间</view>
						<view class="fvalue">
							<picker mode="time" :value="venueInfo.tradeStartTime" @change="onChooseStartTime">
								<view class="fvalue" >
									{{ venueInfo.tradeStartTime || '请选择营业开始时间' }}
								</view>
							</picker>
						</view>
					</view>
				</view>
				<view class="height30"></view>
				<view>
					<view class="form-row">
						<view class="ftitle"><text class="required">*</text>结束时间</view>
						<view  class="fvalue">
							<picker mode="time" :value="venueInfo.tradeEndTime" @change="onChooseEndTime">
								<view class="fvalue" >
									{{ venueInfo.tradeEndTime || '请选择营业结束时间' }}
								</view>
							</picker>
						</view>
					</view>
				</view>
			</view>
			
			<view class="height30 bg-f1f1f1"></view>
			<view class="venueForm">
				<view class="describe" style="font-size: 28rpx;line-height: 40rpx;">
					<view class="title" style="font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;">本平台为您场馆提供以下推荐服务：</view>
					<view>1、全域推广应用，搜索优质化流量；</view>
					<view>2、接入政府平台，提升品牌影响力；</view>
					<view>3、接入各大商超，满足多样化需求；</view>
					<view>4、服务运动人群，激发运动的热情。</view>
				</view>
				<view>
					<view class="text required red" style="font-size: 32rpx;line-height: 60rpx;color: red;">通过本平台运营获取的收益部分将收取5%服务费</view>
					<view style="padding-top: 20rpx;">
						<u-radio-group v-model="venueInfo.agencyOption" placement="row" activeColor="#06ADAB">
							<u-radio size="35rpx" name="1" label="是" labelSize="33rpx"></u-radio>
							<u-radio size="35rpx" name="0" label="否" :customStyle="{marginLeft: '30rpx'}" labelSize="33rpx"></u-radio>
						</u-radio-group>
					</view>
				</view>
			</view>
			
			<view class="height30 bg-f1f1f1"></view>
			<view class="venueForm">
				<view>
					<view>
						<view style="font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;">请上传相关凭证</view>
						<view style="color: #888888;font-size: 26rpx;line-height: 70rpx;">请拍摄上传您的营业执照/合同书</view>
					</view>
					<view>
						<view>
							<u-upload name="documentImg" :fileList="documentImgList" @afterRead="onUpload($event, 'documentImg')"
								@delete="onDelete($event, 'documentImg')"  :maxCount="1"  width="400" height="400">
								<view class="upload" style="">
									<view class="picture" style="width: 600rpx;">
										<image src="../../../../static/image/yyzz.png"  style="width: 400rpx;height: 400rpx;" mode="widthFix"></image>
									</view>
								</view>
							</u-upload>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view style="padding-top: 30rpx;position: sticky;bottom: 0px;z-index: 10;background-color: #ffffff;">
			<view style="padding: 20rpx 40rpx;">
				<u-button text="提交审批" @click="submitNenueApply" color="#155CCF"></u-button>
			</view>
		</view>
		<!-- 省市区控件 -->
		<u-picker
		     @cancel="pickerLocal.showLocal = false"
		     @close="pickerLocal.showLocal = false"
		     :show="pickerLocal.showLocal"
		     :columns="pickerLocal.addressColumns"
		     @confirm="localConfirm"
		     title="请选择所属区域"
		     keyName="name"
		     itemHeight="80"
		     closeOnClickOverlay
		     ref="uPicker"
		     @change="changeHandler"
		     :defaultIndex="pickerLocal.defaultAddress"
		     immediateChange
		   ></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//场馆ID
				venueId: '',
				//场馆首页图片
				hostList: [],
				//营业执照或合同
				documentImgList: [],
				//提交表单
				venueInfo: {
					//公司名称
					companyName: '',
					//场馆名称
					venueName: '',
					//面积
					area: '',
					
					//联系人
					contacts: '',
					//联系电话
					phone: '',
					//营业开始事件
					tradeStartTime: '',
					//营业结束事件
					tradeEndTime: '',
					//场馆介绍
					venueDescription: '',
					//预约须知
					reservationNotice: '',
					//运营获取收益部分收取5%服务费 0是1否
					agencyOption: '1',
					//场馆位置org，格式：省，市，区
					org: '',
					//经度
					lng: '',
					//纬度
					lat: '',
					//场馆详细地址
					address: '',
					secondLevelOrg: '',
					thirdLevelOrg: '',
					fourthLevelOrg: '',
					//营业执照或合同，单文件
					documentImg: '',
					//当前登录用户
					userId: uni.getStorageSync('userId')
				},
				//场馆设施
				facilitieList: [],
				//已选场馆设施
				facilitieChooseList: [],
				//场馆服务
				serviceList: [],
				//已选场馆服务
				serviceChooseList: [],
				//行政区划选择
				pickerLocal:{
					//区域
					local: '',
					//展示弹出层
					showLocal: false,
					//数据数组
					addressColumns: [],
					//默认选中
					defaultAddress: [],
					//原始数据
					addressData: []
				}
			}
		},
		onLoad() {
			this.merchantVenue();
		},
		onUnload(){
			uni.$off("callLocationAddr");
		},
		methods: {
			//获取场馆信息
			merchantVenue(){
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				this.$request({
					url: `/blade-merchant-app/merchant-app/venue/getVenue`,
					type: 'GET'
				}).then(res => {
					uni.hideLoading();
					//重组数据，将图片转成数组
					var venueData = res.data;
					
					if(venueData.status == 0){
						uni.showModal({
						   title: '场馆审核中',
						   content: '审批需要1-3个工作日，请返回首页等待',
						   showCancel: false,
						   success: function (res) {
							   if (res.confirm) {
								    uni.navigateBack()
							   }
						   }
						});
						return false;
					}
					
					//场馆ID赋值
					this.venueId = venueData.id;
					//其他参数赋值
					var venueInfo = {
						//公司名称
						companyName: venueData.companyName,
						//场馆名称
						venueName: venueData.venueName,
						//面积
						area: venueData.area,
						//联系人
						contacts: venueData.contacts,
						//联系电话
						phone: venueData.phone,
						//营业开始事件
						tradeStartTime: venueData.tradeStartTime,
						//营业结束事件
						tradeEndTime: venueData.tradeEndTime,
						//场馆介绍
						venueDescription: venueData.venueDescription,
						//预约须知
						reservationNotice: venueData.reservationNotice,
						//运营获取收益部分收取5%服务费 0是1否
						agencyOption: venueData.agencyOption.toString(),
						//场馆位置org，格式：省，市，区
						org: venueData.org,
						//经度
						lng: venueData.lng,
						//纬度
						lat: venueData.lat,
						//场馆详细地址
						address: venueData.address,
						secondLevelOrg: venueData.secondLevelOrg,
						thirdLevelOrg: venueData.thirdLevelOrg,
						fourthLevelOrg: venueData.fourthLevelOrg,
						//营业执照或合同，单文件
						documentImg: venueData.documentImg,
						//当前登录用户
						userId: venueData.userId
					};
					//场馆服务
					this.serviceChooseList = venueData.services.split(",");
					//场馆设施
					this.facilitieChooseList = venueData.facilities.split(",");
					//场馆主图，多张图
					var hostList = venueData.img.split(',');
					var newHostList = [];
					hostList.forEach(item => {
						var d = { url: item };
						newHostList.push(d);
					});
					this.hostList = newHostList;
					//营业执照（1张图）
					this.documentImgList = [{ url: venueData.documentImg }];
					
					//场馆信息
					this.venueInfo = venueInfo;
					this.vunueInitData();
				}).catch(err =>{
					
				})
			},
			
			//页面初始化
			vunueInitData(){
				//场馆设施
				this.fetchVenuePlan();
				//场馆服务
				this.fetchVenueService();
				//场馆省市区原始
				this.fetchAddressList();
				var that = this;
				uni.$on("callLocationAddr",(data) => {
					this.venueInfo.address = data.address;
					this.venueInfo.lat = data.latitude;
					this.venueInfo.lng = data.longitude;
				});
			},
			// 获取场馆设施
			fetchVenuePlan() {
				this.$request({
					url: '/blade-client-business/app/dict/getVenueFacilities'
				}).then(res => {
					if (res?.code === 200) {
						this.facilitieList = res.data;
					}
				})
			},
			// 获取场馆服务
			fetchVenueService() {
				this.$request({
					url: '/blade-client-business/app/dict/getVenueServices'
				}).then(res => {
					if (res?.code === 200) {
						this.serviceList = res.data;
					}
				})
			},
			// 选择场馆设施
			onChoosePlan(record) {
				const index = this.facilitieChooseList.findIndex(item => item === record.dictKey);
				if (index >= 0) {
					this.facilitieChooseList.splice(index, 1);
				} else {
					this.facilitieChooseList.push(record.dictKey);
				}
			},
			// 选择场馆服务
			onChooseService(record) {
				const index = this.serviceChooseList.findIndex(item => item === record.dictKey);
				if (index >= 0) {
					this.serviceChooseList.splice(index, 1);
				} else {
					this.serviceChooseList.push(record.dictKey);
				}
			},
			// 选择开始时间
			onChooseStartTime(e) {
				this.venueInfo.tradeStartTime = e.detail.value;
			},
			// 选择结束时间
			onChooseEndTime(e) {
				this.venueInfo.tradeEndTime = e.detail.value;
			},
			//下一步保存按钮事件
			submitNenueApply(){
				if(this.hostList.length<=0){
					uni.$u.toast("请上传场馆图片")
					return ;
				}
				if(!this.venueInfo.companyName){
					uni.$u.toast("请输入公司名称")
					return ;
				}
				if(!this.venueInfo.venueName){
					uni.$u.toast("请输入场馆名称")
					return ;
				}
				
				if(!this.venueInfo.area){
					uni.$u.toast("请输入场馆占地面积")
					return ;
				}
				if(!this.venueInfo.contacts){
					uni.$u.toast("请输入场馆联系人")
					return ;
				}
				if(!this.venueInfo.phone){
					uni.$u.toast("请输入联系电话")
					return ;
				}
				if(!this.venueInfo.address){
					uni.$u.toast("请输入详细地址")
					return ;
				}
				
				if(this.facilitieChooseList.length<=0){
					uni.$u.toast("请选择场馆的已有设施")
					return ;
				}
				if(this.serviceChooseList.length<=0){
					uni.$u.toast("请选择场馆的服务")
					return ;
				}
				if(!this.venueInfo.venueDescription){
					uni.$u.toast("请输入场馆介绍")
					return ;
				}
				if(!this.venueInfo.reservationNotice){
					uni.$u.toast("请输入预约须知")
					return ;
				}
				
				if(this.documentImgList.length<=0){
					uni.$u.toast("请上传营业执照或合同书")
					return ;
				}
				
				let that=this
				uni.showModal({
					title: '提示',
					content: '确认场馆资料填写无误，提交审批?',
					success: function(res) {
						if (res.confirm) {
							that.saveVenueApply();
						}
					}
				});
			},
			//提交保存
			saveVenueApply(){
				const params = {
					...this.venueInfo
				};
				
				params.img = this.hostList.map(item => item.url).join(',');
				params.documentImg = this.documentImgList.map(item => item.url).join(',');
				
				params.facilities = this.facilitieChooseList.join(',');
				params.services = this.serviceChooseList.join(',');
				//默认0待审核重新提交
				params.status = 0;
				params.id = this.venueId;
				
				uni.showLoading({
					title: '保存中',
					mask: true
				})
				this.$request({
					url: `/blade-merchant-app/merchant-app/venue/updateVenue`,
					type: 'POST',
					data: params
				}).then(res => {
					uni.hideLoading();
					if(res.code == 200){
						uni.showModal({
						   title: '申请成功',
						   content: '审批需要1-3个工作日，请留意您手机短信查看审批消息',
						   showCancel: false,
						   success: function (res) {
							   if (res.confirm) {
								    uni.navigateBack()
							   }
						   }
						});
					} else {
						uni.showModal({
						   title: '申请失败',
						   content: res.msg,
						   showCancel: false,
						   success: function (res) {}
						});
					}
				}).catch(err =>{
					
				})
			},
			// 上传文件
			onUpload(files, type) {
				const {
					file
				} = files;
				let index = this[`${type}List`].length;
				this[`${type}List`].push({
					...file,
					status: 'uploading',
					message: '上传中'
				})
				this.$utils.onUploadFile(file.url)
					.then(res => {
						let item = this[`${type}List`][index];
						this[`${type}List`].splice(index, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: res.data.link
						}))
					})
			},
			// 删除图片
			onDelete(e, type) {
				this[`${type}List`].splice(e.index, 1);
			},
			//获取地址
			fetchAddressList() {
				this.$request({
					url: '/blade-client-business/app/organization/list',
					data: {}
				}).then(res => {
					if (res?.code === 200) {
						const {
							data
						} = res;
						var addressData = data[0];
						this.pickerLocal.addressData = [addressData];
						// this.pickerLocal.local = addressData.deptName+"-"+addressData.children[0].deptName+"-"+addressData.children[0].children[0].deptName;
						this.addressPickData();
					}
				})
			},
			addressPickData(){
				//省的数组
				const provinceData = this.pickerLocal.addressData.map(e => {
					return { name: e.deptName, code: e.id }//这里可以直接return e.name  这里我是要用到code所以才用对象包起来的 下面的市 区 也一样
				})
				//市的数组
				const cityData = this.pickerLocal.addressData.map(e => {
					const arr = []
					arr.push(
					  e.children.map(c => {
						return { name: c.deptName, code: c.id }
						  
					  })
					)
					return arr
				})
				//区的数组
				const areaData = this.pickerLocal.addressData.map(e => {
					const arr = []
					arr.push(
					  e.children.map(c =>
						c.children.map(d => {
						  return { name: d.deptName, code: d.id }
						})
					  )
					)
					return arr
				})
				const arr = [provinceData, cityData[0][0], areaData[0][0][0]]
				this.pickerLocal.addressColumns = arr    //将得到的3个数组 的第一个市的所有数据赋值 作为初始数据
				this.backfill();
			},
			changeHandler(e) {
				//分别表示选中的列 , 该列的第几个,选中的3列的第几个的数组,组件本身
				const { columnIndex, index, indexs, picker = this.$refs.uPicker } = e
			   //如果改变的是第一列
				if (columnIndex === 0) {
				  const children1 = this.pickerLocal.addressData[index].children.map(e => {
					return { name: e.deptName, code: e.id }
				  })
				  picker.setColumnValues(1, children1)
				//更换 第二列数据
				  const children2 = this.pickerLocal.addressData[index].children[indexs[1]].children.map(e => {
					return { name: e.deptName, code: e.id }
				  })
				  picker.setColumnValues(2, children2)
				//更换 第三列数据
				}
				if (columnIndex === 1) {
					//如果改变的是第二列
				  const children3 = this.pickerLocal.addressData[indexs[0]].children[indexs[1]].children.map(e => {
					return { name: e.deptName, code: e.id }
				  })
				  picker.setColumnValues(2, children3)
					//更换 第三列数据
				}
			},
			localConfirm(e) {
				//显而易见 不多赘述
				this.pickerLocal.local = `${e.value[0].name}-${e.value[1].name}-${e.value[2].name}`
				// this.pickerLocal.localCode = `${e.value[0].code}-${e.value[1].code}-${e.value[2].code}`
				this.venueInfo.org =  `${e.value[2].code}`;
				this.venueInfo.secondLevelOrg =  `${e.value[0].code}`;
				this.venueInfo.thirdLevelOrg =  `${e.value[1].code}`;
				this.venueInfo.fourthLevelOrg =  `${e.value[2].code}`;
				
				this.pickerLocal.showLocal = false
			},
			//已经知道了 this.local ='省-市-区'初始弹窗时默认选中改值
			
			backfill() {
				
				var secondLevelOrg = this.venueInfo.secondLevelOrg;
				var thirdLevelOrg = this.venueInfo.thirdLevelOrg;
				var fourthLevelOrg = this.venueInfo.fourthLevelOrg;
				
				let index,
				  index1,
				  index2 = 0
				let arr,
				  arr1,
				  arr2 = []
				//匹配省市区对应每列的第几个
				this.pickerLocal.addressData.forEach((item, i) => {
				  if (item.id == secondLevelOrg) {
					index = i
					item.children.forEach((val, ind) => {
					  if (val.id == thirdLevelOrg) {
						index1 = ind
						val.children.forEach((e, n) => {
						  if (e.id == fourthLevelOrg) {
							index2 = n
						  }
						})
					  }
					})
				  }
				})
				
				arr = this.pickerLocal.addressData.map(e => {
				  return { name: e.deptName, code: e.id }
				})
				arr1 = this.pickerLocal.addressData[index].children.map(e => {
				  return { name: e.deptName, code: e.id }
				})
				arr2 = this.pickerLocal.addressData[index].children[index1].children.map(e => {
				  return { name: e.deptName, code: e.id }
				})
				//反推出3列的数组数据
				this.pickerLocal.addressColumns = [arr, arr1, arr2]
				// 赋值给 默认初始选中 
				this.pickerLocal.defaultAddress = [index, index1, index2];
				this.pickerLocal.local = arr[index].name+'-'+arr1[index1].name+'-'+arr2[index2].name;
			},
			//选择地址获取经纬度
			selectChoose() {
				var url = '/pagesWorkbenches/pages/amap-choose';
				uni.navigateTo({
					url: url
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f1f1f1;
		
		.bg-f1f1f1 {
			background: #f1f1f1;
		}
		
		.height30 {
			height: 30rpx;
		}
		
		.venueForm {
			padding: 40rpx;
			background-color: #ffffff;
			
			.textareaTitle {
				padding-bottom: 20rpx;font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;
				
				.required {
					color: red;
				}
			}
			
			.form-row {
				border-radius: 0rpx;display: flex;border: 1px solid #c3c3c3;justify-content: center;align-items: center; 
				
				.ftitle {
					text-align: center;
					font-size: 30rpx;
					width: 180rpx;
					display: inline-table;
					color: #333333;
					padding:0rpx 10rpx;
					
					.required {
						color: red;
					}
				}
				.fvalue {
					height: 90rpx;width: 100%;font-size: 32rpx;line-height: 90rpx;overflow: hidden;
				}
				
				.multiple {
					display: flex;
					flex-direction: row;
					flex-wrap: wrap;
					padding: 25rpx 0;
				
					view {
						width: 23%;
						margin-left: 2.666%;
						font-size: 26rpx;
						color: #2979ff;
						line-height: 68rpx;
						text-align: center;
						border-radius: 10rpx;
						background-color: #ecf5ff;
				
						&.active {
							position: relative;
				
							&::after {
								content: "";
								position: absolute;
								top: 0;
								left: 0;
								right: 0;
								bottom: 0;
								border: 2rpx solid #2979ff;
								border-radius: 10rpx;
							}
						}
				
						&:nth-child(4n + 1) {
							margin-left: 0;
						}
				
						&:nth-child(n + 5) {
							margin-top: 12rpx;
						}
					}
				}
			}
			
			.submitBtn {
				height: 90rpx;background-color: #0544ab;color: #ffffff;line-height: 90rpx;font-size: 32rpx;
			}
			
		}
	}

</style>
